package org.yefei.homeworkday29.one1;

import java.io.*;
import java.net.*;
import java.util.*;

public class ServerThread extends Thread {
	// 1:服务器上存有多个用户对象（包括用户和密码），客户端通过socket登录，如果成功，输出欢迎信息，失败给出提示。
	private Socket s;

	public ServerThread(Socket s) {
		this.s = s;
	}

	private List<User> list = new LinkedList<User>();
	{
		list.add(new User("tom", "123"));
		list.add(new User("jerry", "1234"));
		list.add(new User("jim", "12345"));
		list.add(new User("鲁迅", "321"));
		list.add(new User("周树人", "431"));
	}

	@Override
	public void run() {
		ObjectInputStream ois = null;
		ObjectOutputStream oos = null;
		try {
			OutputStream os = s.getOutputStream();
			// 传对象
			oos = new ObjectOutputStream(os);
			// oos.writeObject(list);
			// 接收对象输入的用户名和密码

			InputStream is = s.getInputStream();
			ois = new ObjectInputStream(is);

			// 判断并给出回应
			PrintWriter p = new PrintWriter(os);
			while (true) {
				User user = (User) ois.readObject();
				if (list.contains(user)) {
					p.println("欢迎登录！");
					p.flush();
					break;
				} else {
					p.println("用户名和密码不正确，请重新输入！");
					p.flush();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (oos != null)
				try {
					oos.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			if (s != null)
				try {
					s.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			if (ois != null)
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}

	}
}
